from app import db
from app.models.banner import Banner


class BannerService:
    """轮播图 Service"""

    @staticmethod
    def list_banners(banner_type: int = None, page: int = 1, limit: int = 10):
        query = Banner.query
        if banner_type:
            query = query.filter(Banner.type == banner_type)
        pagination = query.order_by(Banner.sort_order.asc(), Banner.created_at.desc()).paginate(page=page, per_page=limit, error_out=False)
        return [b.to_dict() for b in pagination.items], pagination.total

    @staticmethod
    def create_banner(data: dict):
        banner = Banner(
            title=data.get('title'),
            image_url=data.get('image'),
            link_url=data.get('link'),
            type=int(data.get('type', 1)),
            sort_order=int(data.get('sort', 0)),
            status=bool(data.get('status', True))
        )
        db.session.add(banner)
        db.session.commit()
        return banner.to_dict()

    @staticmethod
    def update_banner(banner_id: int, data: dict):
        banner = Banner.query.get(banner_id)
        if not banner:
            return None
        banner.title = data.get('title', banner.title)
        banner.image_url = data.get('image', banner.image_url)
        banner.link_url = data.get('link', banner.link_url)
        banner.type = int(data.get('type', banner.type))
        banner.sort_order = int(data.get('sort', banner.sort_order))
        banner.status = bool(data.get('status', banner.status))
        db.session.commit()
        return banner.to_dict()

    @staticmethod
    def delete_banner(banner_id: int) -> bool:
        banner = Banner.query.get(banner_id)
        if not banner:
            return False
        db.session.delete(banner)
        db.session.commit()
        return True 